package wallpaper;

import lombok.Data;
import org.htmlparser.Node;
import org.htmlparser.NodeFilter;
import org.htmlparser.Parser;
import org.htmlparser.filters.HasAttributeFilter;
import org.htmlparser.filters.TagNameFilter;
import org.htmlparser.util.NodeList;
import org.htmlparser.util.ParserException;
import org.junit.Test;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * author Veng Su
 * email  1344114844@qq.com
 * date   18-9-15 下午12:25
 * 图片链接类
 */

@Data
public class Links {
    private String website = "https://alpha.wallhaven.cc";
    private String filter = "";
    private String url="https://alpha.wallhaven.cc/random?page=2";
    ArrayList<String> urls;
    URL obj;
    HttpURLConnection con;


    public Links() throws IOException {
        obj = new URL(url);
        con = (HttpURLConnection) obj.openConnection();
        con.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36");
        con.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.9");
        con.setRequestMethod("GET");
    }

    /**
     * 获取图片链接
     *
     * @return 图片链接list
     */
    private ArrayList<String> getImgHeadLinks() throws IOException, ParserException {
        urls = new ArrayList<>();

        int responseCode = con.getResponseCode();
        String responseBody = getResponse(con.getInputStream());

        //访问URL成功
        if (responseCode == 200) {
            Parser parser = new Parser(responseBody);
            NodeFilter filter = new TagNameFilter("img");
            NodeList nodes = parser.extractAllNodesThatMatch(filter);
            NodeList classnode = nodes.extractAllNodesThatMatch(new HasAttributeFilter("class", "lazyload"));
            NodeList datanode = classnode.extractAllNodesThatMatch(new HasAttributeFilter("data-src"));

            Node[] data = datanode.toNodeArray();

            //获取url并写入
            for (Node aData : data) {
                String link = aData.toHtml();
                String[] re = link.split(" ");
                String[] rs = re[3].split("\"");
                String headimg = rs[1];
                urls.add(headimg);
            }
        }
        return urls;
    }

    /**
     * 拿到原图下载链接
     * @return list
     * @throws IOException 异常
     * @throws ParserException 异常
     */
    private ArrayList<String> getImgLinks() throws IOException, ParserException {
        urls = new ArrayList<>();
        urls=getImgHeadLinks();
        urls=change(urls);
        return urls;
    }

    /**
     * 转化链接
     * @param urls 缩略图链接
     * @return 原图链接 TODO:: 需要实现
     */
    private ArrayList<String> change(ArrayList<String> urls) {
        return null;
    }

    /**
     * 检查url是否可达
     *
     * @param urls urls
     */
    private void saveWithCheck(ArrayList<String> urls) throws IOException {
        ArrayList<String> new_url = checkUrlList(urls);
        save(new_url, "src/main/java/wallpaper/urls_withcheck.txt");
    }

    /**
     * 不检查url是否可达
     *
     * @param urls url
     */
    private void saveWithoutCheck(ArrayList<String> urls) {
        save(urls, "src/main/java/wallpaper/urls_withoutcheck.txt");
    }

    /**
     * 保存文件
     *
     * @param urls      链接
     * @param file_path 文件路径
     */
    private void save(ArrayList<String> urls, String file_path) {
        try {
            File file = new File(file_path);
            FileOutputStream fileOutputStream = new FileOutputStream(file);

            for (String s : urls
            ) {
                s += "\r\n";
                fileOutputStream.write(s.getBytes());
            }
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("保存失败");
        }
    }

    private ArrayList<String> checkUrlList(ArrayList<String> urls) throws IOException {
        for (String s :
                urls) {
            if (!checkUrlOK(s)) {
                urls.remove(s);
            }
        }
        return urls;
    }


    /**
     * 写入内容到文件
     *
     * @param content 内容
     * @return 是否成功
     */
    private boolean writeToFile(byte[] content) {
        try {
            File list = new File("src/main/java/wallpaper/list.html");
            FileOutputStream outputStream = new FileOutputStream(list);

            outputStream.write(content);
            outputStream.close();
            return true;
        } catch (Exception e) {
            System.out.println("写入失败");
            return false;
        }
    }

    /**
     * 检查URL是否能够访问成功
     *
     * @param url_str url
     * @return 布尔值
     * @throws IOException 读写
     */
    private boolean checkUrlOK(String url_str) throws IOException {
        URL url = new URL(url_str);
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        con.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36");
        con.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.9");
        con.setRequestMethod("GET");
        int responseCode = con.getResponseCode();
        return responseCode == 200;

    }

    /**
     * 将response 字节流转化为string
     *
     * @param is 输入流
     * @return string
     * @throws IOException 读取失败
     */
    private String getResponse(InputStream is) throws IOException {
        String inputLine;
        BufferedReader in = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8));
        StringBuilder rs = new StringBuilder();

        while ((inputLine = in.readLine()) != null) {
            rs.append(inputLine);
        }
        in.close();

        return rs.toString();
    }



    @Test
    public void testGetLinks() throws Exception {
        Links links = new Links();
        List<String> urls = links.getImgHeadLinks();
        for (String s :
                urls) {
            System.out.println(s);
        }
    }
}
